// pages/location/userUpdate/userAdd.ts
import { getIDCard, setUserInfo } from '../../../http/api/userServiceApi'
const { Config } = require('../../../lib/config')
const BASE_UPLOAD_URL = Config.BASE_UPLOAD_URL
const BASE_URL = Config.BASE_URL
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        linkman: '', // 昵称
        linemanTip: '',
        phone: '', // 电话
        phoneTip: '',
        fileList: [], // 头像上传
        avatarUrl: '', // 头像链接
        sfzList: [], // 身份证上传
        // 身份证信息
        sfzInfo: {
            realName: '', // 真实姓名
            realNameTip: '',
            idCard: '', // 身份证号码
            idCardTip: '',
            sex: '1' // 性别
        },
        // 用户类型
        userType: wx.getStorageSync('user-type')
    } as any,

    handleAdd(e: any) {
        const { fileList }: any = this.data
        const { files } = e.detail

        // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
        this.setData({
            fileList: [...fileList, ...files] // 此时设置了 fileList 之后才会展示选择的图片
        })
        console.log(this.data.fileList)
        this.uploadFile(this.data.fileList[0])
    },
    uploadFile(file: any) {
        const { fileList } = this.data

        this.setData({
            fileList: [...fileList, { ...file, status: 'loading' }]
        })
        const { length } = fileList
        console.log(file.url, '-----file')
        const token = wx.getStorageSync('token')
        const openid = wx.getStorageSync('openid')
        const task = wx.uploadFile({
            url: BASE_UPLOAD_URL + '/api/UploadFile',
            filePath: file.url,
            name: 'file',
            header: {
                token,
                openid
            },
            formData: { Files: file.url },
            success: (res: any) => {
                console.log(res, '---success')
                if (typeof res.data != 'string' && res.data.data.length == 0) {
                    this.setData({
                        avatarUrl: '',
                        fileList: []
                    })
                } else {
                    this.setData({
                        [`fileList[${length}].status`]: 'done'
                    })
                    const { data } = JSON.parse(res.data)
                    const url = `${BASE_UPLOAD_URL}${data[0]}`
                    console.log(url, '---success')
                    this.setData({
                        avatarUrl: url
                    })
                }
            },
            fail: function (error) {
                console.log(error)
            }
        })
        task.onProgressUpdate(res => {
            this.setData({
                [`fileList[${length}].percent`]: res.progress
            })
        })
    },
    handleRemove(e: any) {
        const { index } = e.detail
        const { fileList } = this.data

        fileList.splice(index, 1)
        this.setData({
            fileList
        })
    },

    handleSFZAdd(e: any) {
        const { sfzList }: any = this.data
        const { files } = e.detail

        // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
        this.setData({
            sfzList: [...sfzList, ...files] // 此时设置了 fileList 之后才会展示选择的图片
        })
        console.log(this.data.sfzList)
        this.uploadSFZFile(this.data.sfzList[0])
    },
    uploadSFZFile(file: any) {
        const { sfzList } = this.data

        this.setData({
            sfzList: [...sfzList, { ...file, status: 'loading' }]
        })
        const { length } = sfzList
        console.log(file.url, '-----file')
        const token = wx.getStorageSync('token')
        const openid = wx.getStorageSync('openid')
        const task = wx.uploadFile({
            url: BASE_UPLOAD_URL + '/api/UploadFile', // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'file',
            header: {
                token,
                openid
            },
            formData: { Files: file.url },
            success: async (res: any) => {
                const { data } = JSON.parse(res.data)
                const url = `${BASE_UPLOAD_URL}${data[0]}`
                console.log(url, '---success')
                const idCardRes: any = await getIDCard(url)
                console.log(idCardRes, '----BASE_URL')
                if (typeof res.data != 'string' && idCardRes.data.data.length == 0) {
                    this.setData({
                        sfzList: []
                    })
                } else {
                    const userInfo = idCardRes.data.data[0]
                    console.log(userInfo)
                    this.setData({
                        sfzInfo: {
                            ...this.data.sfzInfo,
                            realName: userInfo.name,
                            idCard: userInfo.id,
                            sex: userInfo.gender == '男' ? '1' : '2'
                        }
                    })
                    this.setData({
                        [`sfzList[${length}].status`]: 'done'
                    })
                }
            },
            fail: function (error) {
                console.log(error, '----error')
            }
        })
        task.onProgressUpdate(res => {
            this.setData({
                [`fileList[${length}].percent`]: res.progress
            })
        })
    },
    handleSFZRemove(e: any) {
        const { index } = e.detail
        const { sfzList } = this.data

        sfzList.splice(index, 1)
        this.setData({
            sfzList
        })
    },

    async add() {
        const { linkman, phone, avatarUrl, sfzInfo, userType } = this.data
        console.log(linkman, phone, avatarUrl, sfzInfo)
        if (!this.valid()) {
            return
        }
        const userInfo = {
            user_icon: avatarUrl, //用户的头像
            user_sname: linkman, //用户的昵称
            user_name: sfzInfo.realName, //用户的真实姓名
            user_tel: phone, //用户的电话
            user_card: sfzInfo.idCard, //用户的身份证号码
            user_sex: sfzInfo.sex == '男' ? '1' : '2' //用户性别 0未知 1男 2女
        }
        console.log(userInfo)
        const res = await setUserInfo(userInfo)
        console.log(res, '---res')
        if (userType == 1) {
            await wx.switchTab({
                url: '/pages/my/my'
            })
            app.globalData.tab_value = '/pages/my/my'
        } else {
            await wx.switchTab({
                url: '/pages/driver/my/my'
            })
            app.globalData.tab_value = '/pages/driver/my/my'
        }
    },

    valid() {
        const { linkman, phone, sfzInfo, avatarUrl } = this.data

        if (linkman === '') {
            this.setData({
                linemanTip: '联系人不能为空'
            })
            return false
        } else {
            this.setData({
                linemanTip: ''
            })
        }
        if (phone === '') {
            this.setData({
                phoneTip: '手机号不能为空'
            })
            return false
        } else if (!this.checkTelephone(phone)) {
            this.setData({
                phoneTip: '请输入正确的手机号'
            })
            return false
        } else {
            this.setData({
                phoneTip: ''
            })
        }

        if (avatarUrl == '') {
            wx.showToast({
                title: '未上传头像',
                // @ts-ignore
                icon: 'error',
                duration: 1000
            })
            return false
        }

        if (sfzInfo.realName === '') {
            this.setData({
                sfzInfo: {
                    ...sfzInfo,
                    realNameTip: '真实姓名不能为空'
                }
            })
            return false
        } else {
            this.setData({
                sfzInfo: {
                    ...sfzInfo,
                    realNameTip: ''
                }
            })
        }

        if (sfzInfo.idCard === '') {
            this.setData({
                sfzInfo: {
                    ...sfzInfo,
                    idCardTip: '身份证号码不能为空'
                }
            })
            return false
        } else if (!this.checkIdCard(sfzInfo.idCard)) {
            this.setData({
                sfzInfo: {
                    ...sfzInfo,
                    idCardTip: '请输入正确的身份证号码'
                }
            })
            return false
        } else {
            this.setData({
                sfzInfo: {
                    ...sfzInfo,
                    idCardTip: ''
                }
            })
        }
        return true
    },

    checkTelephone(telephone: string) {
        const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/
        return reg.test(telephone)
    },

    checkIdCard(idCard: string) {
        const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
        return reg.test(idCard)
    },

    handlerSexChange(RadioValue: any) {
        console.log(RadioValue)
        this.setData({
            sfzInfo: {
                ...this.data.sfzInfo,
                sex: RadioValue.detail.value
            }
        })
    },

    handlerPhoneInput(InputValue: any) {
        console.log(InputValue)
        this.setData({
            phone: InputValue.detail.value
        })
    },

    handlerLinkManInput(InputValue: any) {
        console.log(InputValue)
        this.setData({
            linkman: InputValue.detail.value
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {},

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.hideHomeButton()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {}
})
